document.addEventListener('DOMContentLoaded', function() {
    // 头像上传功能
    const changeAvatarBtn = document.getElementById('changeAvatarBtn');
    const avatarFile = document.getElementById('avatarFile');
    const avatarForm = document.getElementById('avatarForm');
    const userAvatar = document.querySelector('.user-avatar');
    
    changeAvatarBtn.addEventListener('click', () => {
        avatarFile.click();
    });
    
    avatarFile.addEventListener('change', (e) => {
        if (e.target.files.length > 0) {
            const formData = new FormData();
            formData.append('file', e.target.files[0]);
            
            // 显示上传中状态
            changeAvatarBtn.disabled = true;
            changeAvatarBtn.textContent = '上传中...';
            
            // 发送请求
            fetch('/api/users/avatar', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新头像显示
                    userAvatar.src = data.data + '?t=' + new Date().getTime();
                    alert('头像更新成功！');
                } else {
                    alert('头像更新失败：' + data.message);
                }
                // 恢复按钮状态
                changeAvatarBtn.disabled = false;
                changeAvatarBtn.textContent = '更换头像';
            })
            .catch(error => {
                console.error('上传失败:', error);
                alert('头像上传失败，请重试');
                // 恢复按钮状态
                changeAvatarBtn.disabled = false;
                changeAvatarBtn.textContent = '更换头像';
            });
        }
    });
    
    // 个人简介编辑功能
    const editBioBtn = document.getElementById('editBioBtn');
    const bioForm = document.getElementById('bioForm');
    const bioText = document.getElementById('bioText');
    const cancelBioEdit = document.getElementById('cancelBioEdit');
    const bioDisplay = document.querySelector('.profile-bio p');
    
    // 添加新字段的引用
    const phoneNumberInput = document.getElementById('phoneNumber');
    const birthDateInput = document.getElementById('birthDate');
    const genderSelect = document.getElementById('gender');
    const locationInput = document.getElementById('location');
    const profileDetailsList = document.querySelector('.profile-details-list');
    
    editBioBtn.addEventListener('click', () => {
        editBioBtn.style.display = 'none';
        bioDisplay.style.display = 'none';
        if (profileDetailsList) {
            profileDetailsList.style.display = 'none';
        }
        bioForm.style.display = 'block';
    });
    
    cancelBioEdit.addEventListener('click', () => {
        bioForm.style.display = 'none';
        bioDisplay.style.display = 'block';
        if (profileDetailsList) {
            profileDetailsList.style.display = 'block';
        }
        editBioBtn.style.display = 'block';
    });
    
    bioForm.addEventListener('submit', (e) => {
        e.preventDefault();
        
        // 构建包含所有字段的数据对象
        const profileData = {
            bio: bioText.value.trim(),
            phoneNumber: phoneNumberInput.value.trim(),
            birthDate: birthDateInput.value,
            gender: genderSelect.value,
            location: locationInput.value.trim()
        };
        
        // 发送更新请求
        fetch('/api/users/profile', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(profileData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 更新显示
                bioDisplay.textContent = profileData.bio || '这个人很懒，什么都没有留下...';
                
                // 更新资料列表
                if (profileDetailsList) {
                    // 清空现有列表
                    profileDetailsList.innerHTML = '';
                    
                    // 添加手机号
                    if (profileData.phoneNumber) {
                        const phoneLi = document.createElement('li');
                        phoneLi.innerHTML = `<strong>手机号：</strong><span>${profileData.phoneNumber}</span>`;
                        profileDetailsList.appendChild(phoneLi);
                    }
                    
                    // 添加出生日期
                    if (profileData.birthDate) {
                        const birthLi = document.createElement('li');
                        birthLi.innerHTML = `<strong>出生日期：</strong><span>${profileData.birthDate}</span>`;
                        profileDetailsList.appendChild(birthLi);
                    }
                    
                    // 添加性别
                    if (profileData.gender) {
                        const genderLi = document.createElement('li');
                        genderLi.innerHTML = `<strong>性别：</strong><span>${profileData.gender}</span>`;
                        profileDetailsList.appendChild(genderLi);
                    }
                    
                    // 添加地区
                    if (profileData.location) {
                        const locationLi = document.createElement('li');
                        locationLi.innerHTML = `<strong>地区：</strong><span>${profileData.location}</span>`;
                        profileDetailsList.appendChild(locationLi);
                    }
                }
                
                bioForm.style.display = 'none';
                bioDisplay.style.display = 'block';
                if (profileDetailsList) {
                    profileDetailsList.style.display = 'block';
                }
                editBioBtn.style.display = 'block';
                alert('个人资料更新成功！');
            } else {
                alert('个人资料更新失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('更新失败:', error);
            alert('个人资料更新失败，请重试');
        });
    });
    
    // 为用户帖子添加悬停效果
    const userPosts = document.querySelectorAll('.user-post-item');
    userPosts.forEach(post => {
        const media = post.querySelector('.post-media');
        if (media.classList.contains('video')) {
            const video = media.querySelector('video');
            
            post.addEventListener('mouseenter', function() {
                video.play();
            });
            
            post.addEventListener('mouseleave', function() {
                video.pause();
                video.currentTime = 0;
            });
        }
        
        // 添加点击跳转到帖子详情
        post.addEventListener('click', function() {
            // 假设每个帖子项都有一个data-post-id属性
            const postId = this.getAttribute('data-post-id');
            if (postId) {
                window.location.href = `/posts/${postId}`;
            }
        });
    });
});